package com.demo.crm.service;

import com.arvato.crm.common.DynamicQueryUtil;
import com.arvato.crm.model.FilterRule;
import com.arvato.crm.model.PagingInfo;
import com.arvato.crm.model.entity.Manager;
import com.arvato.crm.model.entity.Permission;
import com.arvato.crm.model.entity.Role;
import com.arvato.crm.model.enums.RuleOp;
import com.arvato.crm.service.CrudFactory;
import com.arvato.crm.service.CrudService;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

import java.util.*;

/**
 * @author tanshuai
 */
@Service
@DependsOn("crudFactory")
public class ManagerService {

    private CrudService service = CrudFactory.create("manager");

    public Object login(String name, String password) {
        Manager manager = findByName(name);
        if (manager == null) {
            return "该用户不存在";
        }
        if (!StringUtils.equals(DigestUtils.md5Hex(password), manager.getPassword())) {
            return "密码错误";
        }
        if (!StringUtils.equals("1", manager.getStatus().getValue())) {
            return "用户状态不可用";
        }
        return manager;
    }

    public Manager findByName(String name) {
        return service.findOne(new PagingInfo(new FilterRule("name", RuleOp.equal, name)));
    }

    @Transactional
    public boolean edit(Manager manager) {
        if (null != service.findById(manager.getId())) {
            service.edit(manager, String.valueOf(manager.getId()));
        } else {
            service.save(manager);
        }
        return true;
    }

    public List<Permission> getMenus(Manager manager) {
        List<Role> roles = manager.getRoles();

        // 去重
        Set<Permission> permissions = new LinkedHashSet<Permission>();
        for (Role role : roles) {
            permissions.addAll(role.getPermissions());
        }

        // 排序
        List<Permission> list = new ArrayList<Permission>(permissions);
        Collections.sort(list, new Comparator<Permission>() {
            public int compare(Permission o1, Permission o2) {
                return o1.getOrdered() - o2.getOrdered();
            }
        });

        // 删除PermissionType不是MENU的
        Iterator<Permission> iterator = list.iterator();
        while (iterator.hasNext()) {
            Permission permission = iterator.next();
            if ("link".equals(permission.getType().getValue())) {
                iterator.remove();
            }
        }
        return list;
    }
}
